from django.db import models
from django.contrib.auth.models import User, PermissionsMixin, AbstractBaseUser, UserManager, BaseUserManager
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.hashers import make_password
from shortuuidfield import ShortUUIDField


class UserStatusChoices(models.IntegerChoices):
    # 已激活
    ACTIVED = 1
    # 没有激活
    UNACTIVE = 2
    # 锁定
    LOCKED = 3


class OAUserManager(BaseUserManager):
    # 用于指定是否在数据迁移过程中使用事务。
    use_in_migrations = True

    # password在下面有解释怎么来的
    def _create_user(self, realname, email, password, **extra_fields):
        """
        创建用户
        """
        if not realname:
            raise ValueError("必须设置真实姓名")
        # 邮箱标准化
        email = self.normalize_email(email)
        user = self.model(realname=realname, email=email, **extra_fields)
        user.password = make_password(password)
        user.save(using=self._db)
        return user

    # 创建普通用户
    def create_user(self, realname, email=None, password=None, **extra_fields):
        # oa肯定都是员工所以是True
        extra_fields.setdefault("is_staff", True)
        extra_fields.setdefault("is_superuser", True)
        return self._create_user(realname, email, password, **extra_fields)

    # 当你使用 python manage.py createsuperuser命令创建超级用户时，底层就是调用这个函数
    def create_superuser(self, realname, email=None, password=None, **extra_fields):
        """
        创建超级用户
        """
        extra_fields.setdefault("is_staff", True)
        extra_fields.setdefault("is_superuser", True)
        # 这个前面的就是在数据库中的表名，后面设的是默认值
        extra_fields.setdefault("status", UserStatusChoices.ACTIVED)

        if extra_fields.get("is_staff") is not True:
            raise ValueError("超级用户必须设置is_staff=True")
        if extra_fields.get("is_superuser") is not True:
            raise ValueError("超级用户必须设置is_superuser=True")

        return self._create_user(realname, email, password, **extra_fields)


# 重写User模型
class OAUser(AbstractBaseUser, PermissionsMixin):
    """
    自定义得User模型
    """
    # 设置主键，加密后的，一定要先写，与id有关的全删了，重新生成表，数据库表一定要先确定好
    uid = ShortUUIDField(primary_key=True)
    # 继承AbstractBaseUser 就直接有password和last_login字段
    realname = models.CharField(
        max_length=150,
        unique=False,
    )
    # 唯一而且不能为空
    email = models.EmailField(unique=True, blank=False)
    telephone = models.CharField(max_length=20, blank=True)
    is_staff = models.BooleanField(default=True)
    # 得保留，django自己写的有的就调用is_active
    # 只需关注status即可，无需关注is_active
    is_active = models.BooleanField(default=True)
    status = models.IntegerField(choices=UserStatusChoices, default=UserStatusChoices.UNACTIVE)
    date_joined = models.DateTimeField(auto_now_add=True)
    department = models.ForeignKey('OADepartment', on_delete=models.SET_NULL, null=True, related_name='staffs',
                                   related_query_name="staffs")
    # User.objects.all() 中的objects就是这么来的
    objects = OAUserManager()

    EMAIL_FIELD = "email"
    # USERNAME_FIELD是用来做鉴权的
    from django.contrib.auth import authenticate
    # authenticate(reaquest,username="xxx"),其中authenticate会把username的参数,传给USERNAME_FIELD指定的字段
    USERNAME_FIELD = "email"
    # 不能重复包含EMAIL_FIELD和USERNAME_FIELD中已经设置过的值
    REQUIRED_FIELDS = ["realname", "password"]

    def clean(self):
        super().clean()
        self.email = self.__class__.objects.normalize_email(self.email)

    def get_full_name(self):
        return self.realname

    def get_short_name(self):
        """Return the short name for the user."""
        return self.realname


class OADepartment(models.Model):
    name = models.CharField(max_length=100)
    intro = models.CharField(max_length=200)
    # leader
    leader = models.OneToOneField(OAUser, null=True, on_delete=models.SET_NULL, related_name="leader_department",
                                  related_query_name="leader_department")  # related_name就是从USER反向得到leader # related_query_name跨表查询用的
    # manager
    manager = models.ForeignKey(OAUser, null=True, on_delete=models.SET_NULL, related_name="manager_departments",
                                related_query_name="manager_departments")
